package com.integral.personalAccount.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.integral.common.domain.R;
import com.integral.personalAccount.domain.PersonalAccountDo;
import com.integral.personalAccount.service.PersonalAccountService;
import com.integral.utils.ExcelHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/personal")
public class PersonalAccountController {
    private static final String FUN_NAME = "" ;//功能名称,建议英文,中文可能有问题

    @Autowired
    private PersonalAccountService personalService;

    //分页查询
    @GetMapping("")
    @ResponseBody
    public PageInfo<PersonalAccountDo> page(@RequestParam(required = false) Map<String,Object> params){
        QueryWrapper<PersonalAccountDo> queryWrapper = new QueryWrapper<>();
        Integer pageNum = null;
        Integer pageSize = null;
        if (ObjectUtil.isNotEmpty(params)){
            for (String key : params.keySet()) {
                if ("pageNum".equals(key) || "pageSize".equals(key)){
                    continue;
                }
                queryWrapper.like(key,params.get(key));
            }

            pageNum = Integer.parseInt((String) params.get("pageNum"));
            pageSize = Integer.parseInt((String) params.get("pageSize"));
        }

        pageNum = pageNum == null? 1:pageNum;
        pageSize = pageSize == null?10: pageSize;

        PageHelper.startPage(pageNum,pageSize);

        List<PersonalAccountDo> list = personalService.list(queryWrapper);
        return new PageInfo<>(list);
    }

    // 根据条件查询(不分页)
    public List<PersonalAccountDo> selectBy(Map<String,Object> params){
        QueryWrapper<PersonalAccountDo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(params)){
            for (String key : params.keySet()) {
                if ("pageNum".equals(key) || "pageSize".equals(key)){
                    continue;
                }
                queryWrapper.like(key,params.get(key));
            }
        }
        List<PersonalAccountDo> list = personalService.list(queryWrapper);
        return list;
    }

    //新增
    @PostMapping("")
    @ResponseBody
    public R add(@RequestBody PersonalAccountDo personalAccountDo){
        return personalService.add(personalAccountDo);
    }

    // 修改
    @PutMapping("")
    @ResponseBody
    public R update(@RequestBody PersonalAccountDo personalAccountDo){
        return personalService.update(personalAccountDo);
    }

    //删除
    @DeleteMapping("")
    @ResponseBody
    public R remove(String id){
        return personalService.remove(id);
    }

    // 生成批量导入用的模板文件,生成路径在配置文件中配置
    @GetMapping("/getTemplateFile" )
    @ResponseBody
    public R getTemplateFile() {
        String templateFileName = ExcelHelper.generateTemplate(PersonalAccountDo.class, FUN_NAME);
        return R.ok().put("templateFileName", templateFileName);
    }

    // 批量导入
    @PostMapping("/importData" )
    @ResponseBody
    public R importData(MultipartHttpServletRequest request) {
        //强转报错
        //MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
        MultipartFile tempUploadFile = request.getFile("fileData" ); //FIXME 【重要】参数名需要换掉??
        if (null == tempUploadFile) {
            return R.error("未读取到文件信息" );
        }
        String orgName = tempUploadFile.getOriginalFilename();
        String extName = FileUtil.extName(orgName);
        // (?!)表示整体忽略大小写, $表示字符串结尾
        String pattern = "(?i)(xlsx)$";
        if (!Pattern.matches(pattern, extName)) {
            return R.error("上传文件必须是xlsx类型");
        }

        List<PersonalAccountDo> list = ExcelHelper.parseUploadData(tempUploadFile, PersonalAccountDo.class);
        return personalService.importData(list);
    }

    // 批量导出
    @PostMapping("/getExportFile" )
    @ResponseBody
    public R getExportFile(@RequestBody(required = false) Map<String, Object> params) {
        List<PersonalAccountDo> list = this.selectBy(params);
        String exportFileName = ExcelHelper.generateExportFile(list, FUN_NAME, PersonalAccountDo.class);
        if (null != exportFileName) {
            return R.ok().put("exportFileName", exportFileName);
        } else {
            return R.error("批量导出失败" );
        }
    }

    // 下载文件
    @PostMapping("/downloadFile/{fileName}" )
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable(name = "fileName" ) String fileName) {
        ExcelHelper.downloadExcelFile(request, response, fileName);
    }

    // 查询成员列表字典
    @GetMapping("/getUsersDict")
    @ResponseBody
    public R getUsersDict(){
        // 由于成员可能存在重名，用 福利群名称_职务_姓名 筛选成员
        List<Map<String,String>> list = new ArrayList<>();
        QueryWrapper<PersonalAccountDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_no","name","welfare_group_name","position_name")
                .isNotNull("welfare_group_name");
        List<PersonalAccountDo> users = personalService.list(queryWrapper);
        for (PersonalAccountDo personalAccountDo : users) {
            String key = String.valueOf(personalAccountDo.getUserNo());
            String label = personalAccountDo.getWelfareGroupName() + "_" + personalAccountDo.getPositionName() +
                    "_" + personalAccountDo.getName();
            Map<String,String> tmpMap = new HashMap<>();
            tmpMap.put("key",key);
            tmpMap.put("value",personalAccountDo.getName());
            tmpMap.put("label",label);
            list.add(tmpMap);
        }
        return R.ok().put("list",list);
    }
}
